package io.gitee.kotle.android.utils

import android.app.Activity
import android.content.ContextWrapper
import android.content.res.Configuration
import android.os.Looper
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import io.gitee.kotle.android.BaseGlobalConst

/*与安卓系统有关的工具类*/
/**
 * [AppCompatActivity]的扩展属性
 */
val AppCompatActivity.appCompatActivity
    get() = this

/**
 * [Fragment]的扩展属性
 */
val Fragment.appCompatActivity: AppCompatActivity
    get() = requireActivity() as AppCompatActivity

/**
 * [View]的扩展属性
 */
val View.appCompatActivity: AppCompatActivity
    get() {
        val ctx = context
        if (ctx is AppCompatActivity) {
            return ctx
        }
        if (ctx is ContextWrapper) {
            return ctx.baseContext as AppCompatActivity
        }
        return ctx as AppCompatActivity
    }

/**
 * [View]的扩展属性
 */
val View.fragment: Fragment
    get() = FragmentManager.findFragment(this)

/**
 * 是否是主线程
 */
val isMainThread: Boolean
    get() = Looper.getMainLooper() === Looper.myLooper()

/**
 * 在主线程运行代码
 */
fun postMainHandler(delay: Long = 0, runnable: Runnable) {
    if (delay > 0) {
        BaseGlobalConst.mainHandler.postDelayed(runnable, delay)
    } else {
        if (isMainThread) {
            runnable.run()
        } else {
            BaseGlobalConst.mainHandler.post(runnable)
        }
    }
}

/**
 * 允许在主线程
 */
fun <T : View> T?.runMainHandle(block: Function1<T, Unit>) {
    this ?: return
    if (isMainThread) {
        block.invoke(this)
    } else {
        this.post {
            block.invoke(this)
        }
    }
}

/**
 * 从[ContextWrapper]中获取[Activity]
 */
fun ContextWrapper.getRealActivity(): Activity? {
    if (this is Activity) {
        return this
    }
    val ctx = this.baseContext ?: return null
    if (ctx is Activity) {
        return ctx
    }
    if (ctx is ContextWrapper) {
        return getRealActivity()
    }
    return null
}

/**
 * 类型转换
 */
inline fun <reified Obj> Any?.asOrNull(): Obj? {
    return if (this is Obj) {
        this
    } else {
        null
    }
}

/**
 * 判断是否是平板，功能待测试
 */
val isPadDevice: Boolean
    get() = ((BaseGlobalConst.app.resources.configuration.screenLayout
            and Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE)
